<?php
namespace Src;

class Pdo
{
    //protected static $_instance = null;
    protected $dsn;
    protected $dbh;
    protected $stmt;
    protected $dbhost;
    protected $dbName;
    protected $dbUser;
    protected $dbPasswd;

    public function __construct()
    {
        try {
            $mysql = Config::getConfig()['mysql'];//读取配置信息
            $this->dbhost = $mysql['hostname'];
            $this->dbName = $mysql['database'];
            $this->dbUser = $mysql['username'];
            $this->dbPasswd = $mysql['password'];
            $this->dsn = 'mysql:host='.$this->dbhost.';dbname='.$this->dbName;
            $this->dbh = new \PDO($this->dsn, $this->dbUser, $this->dbPasswd,array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,\PDO::ATTR_PERSISTENT => false,\PDO::ATTR_STRINGIFY_FETCHES=>false,\PDO::ATTR_EMULATE_PREPARES=>false,\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>false));
			$this->dbh->exec("SET character_set_connection='utf8mb4', character_set_results='utf8mb4', character_set_client=utf8mb4");
        } catch (\PDOException $e) {
            echo Response::json1(40000, $e->getMessage());
            return;
        }
    }

    private function __clone() {}


    //swoole协程应当不建议单例模式
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
    /**
     *
     * sql sql语句
     * array execute的数组[]
     * @return 2维数组
     */
    public function select($sql, $array=[])
    {
    	$this->stmt = $this->dbh->prepare($sql);
		$this->stmt->execute($array);
		return $this->stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     *
     * sql sql语句
     * array execute的数组[]
     * @return 2维数组
     */
    public function update($sql, $array=[])
    {
    	$this->stmt = $this->dbh->prepare($sql);
		$this->stmt->execute($array);
        return $this->stmt->rowCount();
    }
	
	/**
     *
     * sql sql语句
     * array execute的数组[]
     * @return lastInsertId
     */
    public function insert($sql, $array=[])
    {
    	$this->stmt = $this->dbh->prepare($sql);	
		$this->stmt->execute($array);		
    	return $this->dbh->lastInsertId();
    }

    //swoole模式下，可能会有冲突，应弃用
    public function selectYield($sql)
    {
        $this->stmt = $this->dbh->prepare($sql);
        $this->stmt->execute();
        while ($row = $this->stmt->fetch(\PDO::FETCH_ASSOC)) {
            //$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
            //print $data;
            yield $row;
        }
    }

    public function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }

    public function commit()
    {
        $this->dbh->commit();
    }

    public function rollback()
    {
        $this->dbh->rollback();
    } 

    public function __destruct()
    {
        $this->stmt = null;
        $this->dbh = null;
        //echo "pdo is finished".PHP_EOL;
    }
}